﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;

public partial class admin_LogoDetail : SitePage
{
    #region Fields
    public string Command
    {
        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }
        set { ViewState["Command"] = value; }

    }
    public string ThumImage
    {
        get
        {
            object o = ViewState["ThumImage"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ThumImage"] = value; }

    }
    public int LogoId
    {
        get
        {
            object o = ViewState["LogoId"];
            if (o != null) return (int)o;
            return int.MinValue;
        }
        set { ViewState["LogoId"] = value; }

    }
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadData();
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();
        InitPosition();
        InitTarget();
    }

    private void InitPosition()
    {
        foreach (string volume in Enum.GetNames(typeof(enmTemplatePosition)))
        {
            enmTemplatePosition veggie = (enmTemplatePosition)Enum.Parse(typeof(enmTemplatePosition),volume);
            int veggieValue = (int)veggie;
            drlPosition.Items.Add(new ListItem(volume, veggieValue.ToString()));
        }
        drlPosition.SelectedValue = clsQueryString.GetString("F_drlPosition");
    }
    private void InitTarget()
    {
        foreach (string volume in Enum.GetNames(typeof(enmLinkTarget)))
        {
            drlTarget.Items.Add(new ListItem(volume, volume));
        }
        drlTarget.Items.Insert(0,new ListItem("---",string.Empty));
    }
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

    }
    #endregion

    #region Methods
    private void LoadData()
    {
        if (this.Command == "edit")
        {
            busLogo objBus = new busLogo();
            Logo objLogo = objBus.GetByID(this.LogoId);
            if (objLogo != null)
            {
                txtTitle.Text = objLogo.Title.Trim();
                txtTitleEn.Text = objLogo.TitleEn.Trim();
                if (objLogo.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
                this.ThumImage = objLogo.ImageFile;
                txtLink.Text = objLogo.Link;
                drlPosition.SelectedValue = objLogo.Position.ToString();
                drlTarget.SelectedValue = objLogo.Target;
                BindImage(trImage, imgImage, lbtnDeleteImage, objLogo.ImageFile);
            }
        }
    }
    private void InitData()
    {
        string validateGroup = "logoDetail";
        vsumForm.ValidationGroup = btnSave.ValidationGroup = reqTitle.ValidationGroup = cusImage.ValidationGroup = validateGroup;
        //Init message
        reqTitle.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Title");       
        cusImage.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Image");
        this.Command = clsQueryString.GetString("act");
        this.LogoId = clsQueryString.GetInt("id");       
    }

    private void UpdateLogo(Logo objData)
    {
        busLogo objBus = new busLogo();
        objData.LogoId = this.LogoId;
        if (objBus.Update(objData))
            Response.Redirect("LogoList.aspx?" + this.GetPageQuery);
        else lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
    }

    private void InsertLogo(Logo objLogo)
    {
        busLogo objBus = new busLogo();
        if (objBus.Insert(objLogo))
            Response.Redirect("LogoList.aspx?" + this.GetPageQuery);
        else
        {
            this.DeleteImage(objLogo.ImageFile);
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //get datavalue
            Logo objData = new Logo();
            objData.CreatedBy = this.userloginName;
            objData.CreatedDate = clsDateTime.Now;            
            objData.Title = txtTitle.Text.Trim();
            objData.TitleEn = txtTitleEn.Text.Trim();
            objData.Link =txtLink.Text.Trim();
            objData.Position = clsConvert.Byte(drlPosition.SelectedValue.ToString());
            objData.Target = drlTarget.SelectedValue.ToString();          
            objData.ImageFile = UploadThumImage(fulImage, this.ThumImage);            
            if (chkIsActive.Checked)
                objData.IsActive = true;
            else
                objData.IsActive = false;
            objData.UpdatedBy = this.userloginName;
            objData.UpdatedDate = clsDateTime.Now;
            if (objData.Link == string.Empty)
                objData.Target = string.Empty;
            if (this.Command == "edit")
                UpdateLogo(objData);
            else
                InsertLogo(objData);
        }
        else
        {
            vsumForm.ShowMessageBox = false;
            vsumForm.ShowSummary = true;
        }
    }

    private string UploadThumImage(FileUpload _ful, string _oldImage)
    {
        string result = _oldImage;
        if (_ful.HasFile)
        {
            string fileNameUpload = _ful.FileName;
            string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
            string fileName = Guid.NewGuid().ToString();
            result = fileName + extFile;
            string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_LOGO_FOLDER);
            string pathThumb = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_LOGO_THUMBIMAGE_FOLDER);
            if (!string.IsNullOrEmpty(_oldImage))
            {
                this.DeleteImage(_oldImage);
            }
            fullPath += fileName + extFile;
            //pathThumb += fileName + extFile;
            _ful.SaveAs(fullPath);
            //Redrawimage
            //Bitmap bmp = (Bitmap)Bitmap.FromFile(fullPath);
            //if (!clsImage.RewriteImage(bmp, 178, 0, pathThumb))
            //    _ful.SaveAs(pathThumb);
            //bmp.Dispose();
            // delete source image
            //clsFile.DeleteFile(fullPath);
        }
        return result;
    }
    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_LOGO_THUMBIMAGE_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_LOGO_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        string para = this.GetPageQuery;
        Response.Redirect("LogoList.aspx?" + para);
    }
    protected void lbtnDeleteImage_Click(object sender, EventArgs e)
    {   
        //Step 1: Delete Image InDB
        busLogo objBus = new busLogo();
        Logo objTip = objBus.GetByID(this.LogoId);
        if (objTip != null)
        {
            objTip.ImageFile = string.Empty;
            if (objBus.Update(objTip))
            {
                DeleteImage(this.ThumImage);
                Response.Redirect("LogoDetail.aspx?" + this.GetPageQuery);
            }
        }
    }
    private void BindImage(HtmlTableRow trImage, System.Web.UI.WebControls.Image img, LinkButton lbtnDelete, string value)
    {
        string imagePage = "~/" + clsConfigData.DEFAULT_UPLOAD_LOGO_THUMBIMAGE_FOLDER + value;
        if (File.Exists(this.Page.Server.MapPath(imagePage)))
        {
            img.ImageUrl = imagePage;
            lbtnDelete.Visible = true;
            trImage.Visible = true;
        }
        else trImage.Visible = false;
    }
    #endregion

    #region Validate Data
    protected void CheckSImageValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsImage.IsValidImage();
    }
    #endregion
}